﻿#ifndef SERVER2_H
#define SERVER2_H

#include <QObject>
#include <QTcpServer> //监听套接字
#include <QTcpSocket> //通信套接字
#include <QDebug>
#include <QHostAddress>
#include <QProcess>
#include <QMetaType>
#include <QDateTime>
#include <QDataStream>
#include "tankdata.h"
#include "save_file.h"
#include "datachange.h"

extern bool datachange_flag;

//用于存储接收到的数据包
class SocketPacket
{
public:
    int        field_number;    //包计数
    long       length;   //数据长度
    QByteArray data;     //数据
    QByteArray dataType; //数据类型
    bool readdataflag = false;      //读数据标志为
    bool readdataheadflag = false; //读数据头标志为

    SocketPacket()
    {
        length = -1;
    }

    void clear()
    {
        length = -1;
        data.clear();
        dataType.clear();
    }
};

//数据缓存区
class RecvBuffer{
public :
    int packetSize = sizeof(pack_Control_To_PC_Sonar_data);
    QByteArray buffer;
};

class tcpclient2 : public QObject
{
    Q_OBJECT
public:
    explicit tcpclient2(QObject *parent = nullptr);
    ~tcpclient2();

    QTcpSocket *tcpSocket = nullptr; //通信套接字
    QTcpServer *tcpServer = nullptr; //监听套接字


    SocketPacket m_dataPacket;  //用于储存的数据包
    RecvBuffer recvBuffer;
    QVector<pack_Control_To_PC_Sonar_data> pluseInfos;

    bool conectflag = false;

    save_file *m_save_file; //存文件，用于存储声纳数据

    QFile txtFd;

    bool closing = false;

public slots:
    void creattcpclient();
    void write(const char *data, qint64 len);
public:
    void read();
    void read_data();   //网口数据读取函数
    bool parsePacket(QTcpSocket *socket, SocketPacket *packet);

public slots:
    void connectnet(QString IP, quint16 PORT); //连接到网口
    void disconnectnet();   //断开网口
    void sendData(const QString &data);
    void setfilename(QString name);
    void setsavefileflag(bool flag);
    void onReceive();
signals:

    void showstatus(QString);
    void recivedone(QString, Qt::GlobalColor);
    void displaySASTankStatus();
    void displaySonarWorkingStatus();
    void displayPressureHeight();
    void displayAltitudeSensor();


    void canrun();
    void card_state(int);
    void connect_done();    //连接完成信号
    void disconnect_done(); //断开完成信号

    void startdatachange(char *); //开始fft转换
public:
    bool HexSendtcpclient = true;     //16进制发送
    bool Asciitcpclient;         //ASCII模式
private:

    QByteArray m_buffer;    //接收数据缓冲区

    pack_Control_Head *m_pack_Control_Head;
    pack_Control_To_PC_Sonar_data *Sonardata_Data;

    QString filename;       //保存文件名
    bool savedataflag = true;    //ARM端SATA保存数据标志位
    char  tempsonardatabuf[8000]; //临时存放声纳数据，用于FFT转换

    int strHexToDecimal(const QString &strHex);
    char convertHexChar(char ch);
    QByteArray asciiStrToByteArray(const QString &str);
    QByteArray hexStrToByteArray(const QString &str);

};



#endif // SERVER_H
